package activity.LocalFile;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.GridView;

import com.hichip.campro.R;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.TimeZone;

import activity.FishEye.FishEyePlaybackLocalActivity;
import activity.Left.adapter.StickyGridVideoAdapter;
import activity.WallMounted.WallMountedPlayLocalActivity;
import activity.video.PlaybackLocalActivity;
import base.HiFragment;
import bean.LeftLocalFileBean;
import bean.MyCamera;
import butterknife.BindView;
import butterknife.ButterKnife;
import common.HiDataValue;
import custom.stickygridview.GridItem;
import custom.stickygridview.YMComparator;
import utils.SharePreUtils;
public class LocalVideoFragment extends HiFragment implements AdapterView.OnItemClickListener {
    private MyCamera mMyCamera;
    public ArrayList<GridItem> mGirdList=new ArrayList<>();
    private Map<String, Integer> sectionMap = new HashMap<String, Integer>();
    private static int section = 1;
    @BindView(R.id.sticky_gridview) GridView sticky_gridview;
    public  StickyGridVideoAdapter mAdapter;
    public  List<GridItem> mDeleteList = new ArrayList<GridItem>();
    public static final String FILE_PATH = "file_path";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=View.inflate(getActivity(), R.layout.fragment_local_video,null);
        ButterKnife.bind(this,view);
        initViewAndData(view);
        setListeners();
        return view;
    }

    private void setListeners() {
        sticky_gridview.setOnItemClickListener(this);
    }

    private void initViewAndData(View view) {
        initData();
        mAdapter = new StickyGridVideoAdapter(getActivity(), mGirdList, sticky_gridview);
        sticky_gridview.setAdapter(mAdapter);
    }

    private void initData() {
        Bundle bundle=getArguments();
        LeftLocalFileBean bean= (LeftLocalFileBean) bundle.getSerializable("bean");
        for(MyCamera camera: HiDataValue.CameraList){
            if(camera.getUid().equals(bean.getUid())){
                this.mMyCamera=camera;
                break;
            }
        }
        if(mMyCamera==null){
            //说明摄像机被删除了 所以这里随便new 一个
            mMyCamera=new MyCamera(getActivity(),getString(R.string.title_camera_fragment),bean.getUid(),"admin","admin");
            mMyCamera.isWallMounted=SharePreUtils.getBoolean(HiDataValue.CACHE,getActivity(),mMyCamera.getUid()+"isWallMounted");
            HiDataValue.DeleteCameraList.add(mMyCamera);
        }
        File folder=new File(bean.getFile().getAbsolutePath()+"/Download/");
        if(folder!=null&&folder.exists()){
            File[] files=folder.listFiles();
            if(files.length>0){
                for(File file:files){
                    long times = file.lastModified() / 1000;
                    GridItem gridItem=new GridItem(file.getAbsolutePath(),paserTimeToYM(times));
                    gridItem.setType(0);
                    mGirdList.add(gridItem);
                }
            }
        }
        File folderRecord=new File(bean.getFile().getAbsolutePath()+"/VideoRecoding/");
        if(folderRecord!=null&&folderRecord.exists()){
            File[] files=folderRecord.listFiles();
            if(files.length>0){
                for(File file:files){
                    if(file.getName().equals("SnapShot")){
                        continue;
                    }
                    long times = file.lastModified() / 1000;
                    GridItem gridItem=new GridItem(file.getAbsolutePath(),paserTimeToYM(times));
                    gridItem.setType(1);
                    mGirdList.add(gridItem);
                }
            }
        }
        Collections.sort(mGirdList, new YMComparator());
        for (ListIterator<GridItem> it = mGirdList.listIterator(); it.hasNext();) {
            GridItem mGridItem = it.next();
            String ym = mGridItem.getTime();
            if (!sectionMap.containsKey(ym)) {
                mGridItem.setSection(section);
                sectionMap.put(ym, section);
                section++;
            } else {
                mGridItem.setSection(sectionMap.get(ym));
            }
        }
    }



    private String paserTimeToYM(long time) {
        TimeZone tz = TimeZone.getDefault();
        TimeZone.setDefault(tz);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(new Date(time * 1000L));
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position < 0) return;
        mAdapter.playLocal=null;
        if (mAdapter.getDelMode()==1) {
            CheckBox checkBox = (CheckBox) view.findViewById(R.id.grid_cb);
            checkBox.setChecked(checkBox.isChecked() ? false : true);
            if (checkBox.isChecked()) {
                mDeleteList.add(mGirdList.get(position));
            } else {
                mDeleteList.remove(mGirdList.get(position));
            }
            mAdapter.checks[position] = checkBox.isChecked();
        } else {
            GridItem gridItem=mGirdList.get(position);
            Bundle bundle = new Bundle();
            bundle.putString(FILE_PATH,gridItem.getPath());
            bundle.putString(HiDataValue.EXTRAS_KEY_UID, mMyCamera.getUid());

            String strat_time=converStr(gridItem);

            bundle.putString("strat_time", strat_time);
            Intent intent = new Intent();
            if (mMyCamera.isWallMounted) {
                intent.setClass(getActivity(), WallMountedPlayLocalActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
                return;
            }
            if (mMyCamera.isFishEye()) {
                // 初始化鱼眼顶装和壁装的模式
                int num = SharePreUtils.getInt("mInstallMode", getActivity(), mMyCamera.getUid());
                mMyCamera.mInstallMode = num == -1 ? 0 : num;
                intent.setClass(getActivity(), FishEyePlaybackLocalActivity.class);
            } else {
                intent.setClass(getActivity(), PlaybackLocalActivity.class);
            }
            intent.putExtras(bundle);
            startActivity(intent);
        }
    }

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private String  converStr(GridItem gridItem) {
        if(gridItem!=null&& !TextUtils.isEmpty(gridItem.getPath())){
            String [] strings=gridItem.getPath().split("/");
            if(strings.length>0){
                String str=strings[strings.length-1];
                String strTime=str.split("\\.")[0];
                strTime = strTime.replace("_", "");
                try {
                    Date date = new SimpleDateFormat("yyyyMMddHHmmss").parse(strTime);
                    return sdf.format(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                    return "";
                }
            }
        }
        return " ";
    }

}
